//
//  LGInPlaySongListView.swift
//  LGMusic
//
//  Created by 梁尚嘉 on 2017/4/12.
//  Copyright © 2017年 LimeGah. All rights reserved.
//

import UIKit

protocol LGInPlaySongListViewDelegate {
    func didSelectSongAtIndex(_ index:Int) -> Void
}

class LGInPlaySongListView: UIView {

    var delegate:LGInPlaySongListViewDelegate?
    var tableView:UITableView?

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.configure()
    }

    func loadSong(_ song:Song) -> Void {
        let deadlineTime = DispatchTime.now() + .milliseconds(500)
        DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
            self.tableView?.scrollToRow(at: IndexPath.init(row: LGOutPlayBar.sharedBar.currentIndex!, section: 0), at: UITableViewScrollPosition.top, animated: true)
            self.tableView?.reloadData()
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func configure() -> Void {

        self.tableView = UITableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        self.tableView?.register(SongInPlayTableCell.classForCoder(), forCellReuseIdentifier: SongInPlayTableCell.cellIdentifier())
        self.tableView?.backgroundColor = UIColor.clear
        self.tableView?.tableFooterView = UIView.init(frame: CGRect.zero)
        self.tableView?.separatorStyle = UITableViewCellSeparatorStyle.none
        self.tableView?.delegate = self
        self.tableView?.dataSource = self
        self.addSubview(self.tableView!)
        self.tableView?.snp.makeConstraints({ (make) in
            make.left.equalTo(SM_SIZE(20))
            make.right.equalTo(SM_SIZE(-20))
            make.top.bottom.equalTo(0)
        })

    }

}

//MARK: tableivew delegate && datasource
extension LGInPlaySongListView : UITableViewDelegate,UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return (LGOutPlayBar.sharedBar.songs?.count)!
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = SongInPlayTableCell.tableCell(tableView: tableView) as! SongInPlayTableCell
        let song = self.songAt(indexPath)
        cell.configure(song as AnyObject)
        cell.isPlaying = LGOutPlayBar.sharedBar.currentIndex == indexPath.row
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SongInPlayTableCell.cellHeight()
    }

    func songAt(_ indexPath:IndexPath) -> Song {
        return LGOutPlayBar.sharedBar.songs![indexPath.row]
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if (self.delegate != nil && LGOutPlayBar.sharedBar.currentIndex != indexPath.row) {
            self.delegate?.didSelectSongAtIndex(indexPath.row)
        }
    }
    
}
